/**
 * @Title: shiqlamall
 * @Package mall-fe
 * @author Shinelon
 * @date 2017/9/3 15:51
 * @version V1.0
 */
'use strict';

var hogan = require('hogan.js');

var config = {
    serverHost: ''
};

var shiqlamall = {
    request: function (param) {
        var _this = this;
        $.ajax({
            type: param.method || 'get',
            url: param.url || '',
            dataType: param.dataType || 'json',
            data: param.data || '',
            success: function (result) {

                if (0 === result.stats) {
                    //请求成功
                    typeof param.success === 'function' && param.success(result.data, result.msg);
                } else if (10 === result.stats) {
                    //需要强制登录
                    _this.doLogin();
                } else if (1 === result.stats) {
                    //输入数据有错
                    typeof param.success === 'function' && param.error(result.msg);
                }
            },

            error: function (error) {
                typeof param.success === 'function' && param.error(error.statusText);
            }
        })
    },
    //统一获取服务器地址
    getServerUrl: function (path) {
        return config.serverHost + path;
    },
    //获取url参数
    getUrlParam: function (name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
        var result = window.location.search.substr(1).match(reg);
        return result ? decodeURIComponent(result[2]) : null;
    },
    //跳转到登录页面
    doLogin: function () {
        window.location.href = './user-login.html?redirect=' + encodeURIComponent(window.location.href);
    },
    //渲染html 使用hogan 渲染
    renderHtml : function (htmlTtmplate,data) {
        var template = hogan.compile(htmlTtmplate);
        var result = template.render(data);
        return result;
    },
    //成功提示
    successTips: function (msg) {
        alert(msg || '操作成功');
    },
    //错误提示
    errorTips : function (error) {
        alert(error || '操作失败');
    },
    //数据校验
    validate : function (value ,type) {
        var value = $.trim(value);
        //非空验证
        if ('require' === type){
            return !!value;
        }
        //验证手机号
        if('phone' === type){
            return /^1\d{10}$/.test(value);
        }
        //邮箱验证
        if('email' === type){
            return /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/.test(value);
        }
    },
    //返回主页
    goHome :function () {
        window.location.href ='./index.html';
    }
};

module.exports = shiqlamall;

// testing